package com.denghq.projectbuilder.component.aif.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.denghq.projectbuilder.component.aif.RegisterPath;

import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import springfox.documentation.service.Documentation;
import springfox.documentation.spring.web.DocumentationCache;
import springfox.documentation.swagger2.mappers.ServiceModelToSwagger2Mapper;

@Component
public class ApiParser {
	
	private final String  DOC_GROUP = "default";
	private final String  API_VERSION = "1.0.0";
	private final String  API_SCHEME = "http";
	
	@Autowired
	private DocumentationCache documentationCache;

	@Autowired
	private ServiceModelToSwagger2Mapper mapper;
	
	private Operation getOperation(Path path){
		Operation post= path.getPost();
		if(post!=null) return post;

		Operation get= path.getGet();
		if(get!=null) return get;

		Operation delete= path.getDelete();
		if(delete!=null) return delete;

		Operation put= path.getPut();
		if(put!=null) return put;

		Operation patch= path.getPatch();
		if(patch!=null) return patch;

		return new Operation();
	}
	
	private String getMethod(Path path){
		Operation post= path.getPost();
		if(post!=null) return "POST";

		Operation get= path.getGet();
		if(get!=null) return "GET";

		Operation delete= path.getDelete();
		if(delete!=null) return "DELETE";

		Operation put= path.getPut();
		if(put!=null) return "PUT";
		return "POST";
	}

	public List<RegisterPath> getPathSet() {
		List<RegisterPath> res = new ArrayList<RegisterPath>(); 
		Documentation documentation = documentationCache.documentationByGroup(DOC_GROUP);
	    Swagger swagger = mapper.mapDocumentation(documentation);	
	    Map<String ,Path> paths=swagger.getPaths();
	    Set<String> keys=paths.keySet();
	    for(String key:keys){
	    	Path path = paths.get(key);
	    	Operation operation = this.getOperation(path);
	    	String method = getMethod(path);
	    	res.add(new RegisterPath(API_SCHEME, key, API_VERSION, key, operation.getTags()==null?"其他":operation.getTags().get(0), method,  operation.getSummary()));
	    }
		return res;
	}
}
